<template>
  <div class="portfolio-create-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>{{ isEdit ? '编辑组合' : '创建组合' }}</h2>
        </div>
      </template>
      
      <el-form :model="form" label-width="120px" :rules="rules" ref="portfolioForm">
        <el-form-item label="组合名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入组合名称"></el-input>
        </el-form-item>
        
        <el-form-item label="选择策略" prop="strategy">
          <el-select 
            v-model="form.strategy" 
            placeholder="请选择策略" 
            style="width: 100%"
            @change="handleStrategyChange">
            <el-option
              v-for="strategy in strategies"
              :key="strategy.id"
              :label="strategy.name"
              :value="strategy.name">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-divider>组合配置</el-divider>
        
        <el-form-item label="基金选择方式">
          <el-radio-group v-model="form.selectionMethod">
            <el-radio label="auto">策略自动筛选</el-radio>
            <el-radio label="manual">手动选择</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <template v-if="form.selectionMethod === 'auto'">
          <el-form-item label="筛选条件">
            <el-form :inline="true">
              <el-form-item label="基金类型">
                <el-select v-model="form.filterOptions.types" multiple placeholder="选择基金类型">
                  <el-option label="股票型" value="股票型"></el-option>
                  <el-option label="混合型" value="混合型"></el-option>
                  <el-option label="债券型" value="债券型"></el-option>
                  <el-option label="指数型" value="指数型"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="基金规模">
                <el-select v-model="form.filterOptions.size" placeholder="选择规模">
                  <el-option label="不限" value=""></el-option>
                  <el-option label="小于1亿" value="small"></el-option>
                  <el-option label="1-10亿" value="medium"></el-option>
                  <el-option label="大于10亿" value="large"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="基金评级">
                <el-select v-model="form.filterOptions.rating" placeholder="选择评级">
                  <el-option label="不限" value=""></el-option>
                  <el-option label="5星" value="5"></el-option>
                  <el-option label="4星及以上" value="4"></el-option>
                  <el-option label="3星及以上" value="3"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="generatePortfolio">生成组合</el-button>
          </el-form-item>
        </template>
        
        <template v-if="form.selectionMethod === 'manual'">
          <el-form-item label="选择基金" prop="selectedFunds">
            <div class="fund-selection-container">
              <div class="fund-list">
                <h4>可选基金</h4>
                <el-input v-model="fundSearchKeyword" placeholder="搜索基金" clearable></el-input>
                <el-table :data="filteredAvailableFunds" style="width: 100%" height="300px" @row-click="addFundToPortfolio">
                  <el-table-column prop="code" label="代码" width="100"></el-table-column>
                  <el-table-column prop="name" label="名称"></el-table-column>
                  <el-table-column width="50">
                    <template #default>
                      <el-button size="small" type="primary" icon="el-icon-plus" circle></el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              
              <div class="fund-list">
                <h4>已选基金</h4>
                <el-table :data="selectedFundsDetails" style="width: 100%" height="300px">
                  <el-table-column prop="code" label="代码" width="100"></el-table-column>
                  <el-table-column prop="name" label="名称"></el-table-column>
                  <el-table-column label="权重">
                    <template #default="scope">
                      <el-slider
                        v-model="form.weights[scope.$index]"
                        :step="0.05"
                        :min="0"
                        :max="1"
                        show-input
                        :format-tooltip="(val) => val * 100 + '%'">
                      </el-slider>
                    </template>
                  </el-table-column>
                  <el-table-column width="50">
                    <template #default="scope">
                      <el-button size="small" type="danger" icon="el-icon-minus" circle @click="removeFund(scope.$index)"></el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-form-item>
          
          <el-alert
            v-if="!isValidWeights"
            title="权重总和应为 1.0"
            type="warning"
            :closable="false"
            show-icon>
          </el-alert>
        </template>
        
        <div v-if="form.selectedFunds.length > 0" class="selected-funds-summary" style="margin-top: 20px;">
          <h3>已选基金</h3>
          <el-table :data="selectedFundsDetails" style="width: 100%">
            <el-table-column prop="code" label="代码" width="100"></el-table-column>
            <el-table-column prop="name" label="名称" width="180"></el-table-column>
            <el-table-column prop="type" label="类型" width="100"></el-table-column>
            <el-table-column label="权重" width="120">
              <template #default="scope">
                {{ (form.weights[scope.$index] * 100).toFixed(0) }}%
              </template>
            </el-table-column>
            <el-table-column prop="nav" label="最新净值"></el-table-column>
            <el-table-column label="日涨跌幅">
              <template #default="scope">
                <span :class="{ 'red-text': scope.row.dailyReturn > 0, 'green-text': scope.row.dailyReturn < 0 }">
                  {{ (scope.row.dailyReturn * 100).toFixed(2) }}%
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <el-form-item style="margin-top: 20px;">
          <el-button type="primary" @click="submitForm">{{ isEdit ? '保存修改' : '创建组合' }}</el-button>
          <el-button @click="cancel">取消</el-button>
          <el-button v-if="form.selectedFunds.length > 0" type="success" @click="previewPortfolio">预览组合</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 组合预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="组合预览"
      width="800px">
      <div class="portfolio-preview">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="组合名称">{{ form.name }}</el-descriptions-item>
          <el-descriptions-item label="策略名称">{{ form.strategy }}</el-descriptions-item>
          <el-descriptions-item label="基金数量">{{ form.selectedFunds.length }}</el-descriptions-item>
          <el-descriptions-item label="预估年化收益">12.5%</el-descriptions-item>
          <el-descriptions-item label="预估最大回撤">8.3%</el-descriptions-item>
          <el-descriptions-item label="预估波动率">9.2%</el-descriptions-item>
        </el-descriptions>
        
        <div class="portfolio-allocation" style="margin-top: 20px;">
          <h3>资产配置</h3>
          <div class="chart-placeholder" style="height: 300px;">
            <el-empty description="资产配置图表将在此显示"></el-empty>
          </div>
        </div>
        
        <div class="portfolio-backtest" style="margin-top: 20px;">
          <h3>回测表现</h3>
          <div class="chart-placeholder" style="height: 300px;">
            <el-empty description="回测表现图表将在此显示"></el-empty>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="previewDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitForm">保存组合</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'

export default {
  name: 'PortfolioCreate',
  setup() {
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const portfolioForm = ref(null)
    const previewDialogVisible = ref(false)
    const fundSearchKeyword = ref('')
    
    // 判断是否为编辑模式
    const isEdit = computed(() => {
      return route.query.mode === 'edit'
    })
    
    // 表单数据
    const form = reactive({
      id: '',
      name: '',
      strategy: '',
      selectionMethod: 'manual',
      filterOptions: {
        types: [],
        size: '',
        rating: ''
      },
      selectedFunds: [],
      weights: []
    })
    
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入组合名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      strategy: [
        { required: true, message: '请选择策略', trigger: 'change' }
      ],
      selectedFunds: [
        { type: 'array', required: true, message: '请至少选择一个基金', trigger: 'change' }
      ]
    }
    
    // 获取策略列表
    const strategies = computed(() => {
      return store.getters.getStrategies
    })
    
    // 获取基金列表
    const funds = computed(() => {
      return store.getters.getFunds
    })
    
    // 获取已选基金的详细信息
    const selectedFundsDetails = computed(() => {
      return form.selectedFunds.map(fundId => {
        return funds.value.find(fund => fund.id === fundId) || { id: fundId, name: '未知基金', code: '------' }
      })
    })
    
    // 可用基金列表（排除已选）
    const availableFunds = computed(() => {
      return funds.value.filter(fund => !form.selectedFunds.includes(fund.id))
    })
    
    // 过滤后的可用基金列表
    const filteredAvailableFunds = computed(() => {
      if (!fundSearchKeyword.value) return availableFunds.value
      
      const keyword = fundSearchKeyword.value.toLowerCase()
      return availableFunds.value.filter(fund => {
        return fund.name.toLowerCase().includes(keyword) || 
               fund.code.toLowerCase().includes(keyword)
      })
    })
    
    // 计算权重是否有效
    const isValidWeights = computed(() => {
      if (form.selectedFunds.length === 0) {
        return true
      }
      
      const sum = form.weights.reduce((acc, val) => acc + val, 0)
      return Math.abs(sum - 1.0) < 0.01 // 允许0.01的误差
    })
    
    // 监听所选基金变化，初始化权重
    watch(() => form.selectedFunds, (newFunds) => {
      // 初始化每个基金的权重为平均值
      if (newFunds.length > 0) {
        const weight = 1 / newFunds.length
        form.weights = newFunds.map(() => weight)
      } else {
        form.weights = []
      }
    })
    
    // 生命周期钩子
    onMounted(() => {
      // 加载策略和基金数据
      store.dispatch('loadStrategies')
      store.dispatch('loadFunds')
      
      // 如果是编辑模式，从store中获取组合数据
      if (isEdit.value && route.query.id) {
        const portfolioId = parseInt(route.query.id)
        const portfolio = store.getters.getPortfolios.find(p => p.id === portfolioId)
        
        if (portfolio) {
          // 将基金名称转为ID
          const fundIds = portfolio.funds.map(fundName => {
            const fund = funds.value.find(f => f.name === fundName)
            return fund ? fund.id : null
          }).filter(id => id !== null)
          
          form.id = portfolio.id
          form.name = portfolio.name
          form.strategy = portfolio.strategy
          form.selectedFunds = fundIds
          form.weights = [...portfolio.weights]
          form.selectionMethod = 'manual'
        }
      }
      
      // 如果是从策略页面跳转过来，自动选择对应策略
      if (route.query.strategyId) {
        const strategyId = parseInt(route.query.strategyId)
        const strategy = strategies.value.find(s => s.id === strategyId)
        if (strategy) {
          form.strategy = strategy.name
        }
      }
    })
    
    // 处理策略变更
    const handleStrategyChange = (strategyName) => {
      // 这里可以根据选择的策略来推荐基金
      if (form.selectionMethod === 'auto') {
        ElMessage.info('已根据策略更新筛选条件')
      }
    }
    
    // 生成组合（自动选择模式）
    const generatePortfolio = () => {
      if (!form.strategy) {
        ElMessage.warning('请先选择策略')
        return
      }
      
      // 这里实际应该调用API根据策略和筛选条件生成组合
      // 模拟生成操作
      ElMessage.success('组合生成成功')
      
      // 模拟选择了3只基金
      const recommendedFunds = funds.value.slice(0, 3)
      form.selectedFunds = recommendedFunds.map(fund => fund.id)
      
      // 平均权重
      const weight = 1 / form.selectedFunds.length
      form.weights = form.selectedFunds.map(() => weight)
    }
    
    // 添加基金到组合
    const addFundToPortfolio = (fund) => {
      if (!form.selectedFunds.includes(fund.id)) {
        form.selectedFunds.push(fund.id)
      }
    }
    
    // 从组合中移除基金
    const removeFund = (index) => {
      form.selectedFunds.splice(index, 1)
      form.weights.splice(index, 1)
      
      // 重新计算权重
      if (form.selectedFunds.length > 0) {
        const weight = 1 / form.selectedFunds.length
        form.weights = form.selectedFunds.map(() => weight)
      }
    }
    
    // 预览组合
    const previewPortfolio = () => {
      if (!isValidWeights.value) {
        ElMessage.warning('请确保权重总和为1.0')
        return
      }
      
      if (form.selectedFunds.length === 0) {
        ElMessage.warning('请至少选择一只基金')
        return
      }
      
      previewDialogVisible.value = true
    }
    
    // 提交表单
    const submitForm = () => {
      if (!isValidWeights.value) {
        ElMessage.warning('请确保权重总和为1.0')
        return
      }
      
      portfolioForm.value.validate((valid) => {
        if (valid) {
          // 找到策略对象
          const strategyObj = strategies.value.find(s => s.name === form.strategy)
          
          // 创建基金对象列表
          const fundsList = form.selectedFunds.map(fundId => {
            const fund = funds.value.find(f => f.id === fundId)
            return fund ? { id: fundId } : null
          }).filter(fund => fund !== null)
          
          // 创建权重映射
          const weightMap = {}
          form.selectedFunds.forEach((fundId, index) => {
            weightMap[fundId] = form.weights[index]
          })
          
          const portfolioData = {
            name: form.name,
            // 使用策略ID而非策略名称
            strategy: strategyObj ? { id: strategyObj.id } : null,
            // 使用基金对象列表而非基金名称列表
            funds: fundsList,
            // 使用正确格式的权重映射
            weights: weightMap,
            creator: '管理员'
          }
          
          if (isEdit.value) {
            // 编辑已有组合
            const portfolioId = parseInt(route.query.id)
            
            store.dispatch('updatePortfolio', {
              id: portfolioId,
              portfolio: portfolioData
            }).then(() => {
              ElMessage.success('组合更新成功')
              // 关闭预览对话框（如果打开）
              previewDialogVisible.value = false
              // 返回组合列表页面
              router.push('/portfolio-management')
            }).catch(error => {
              ElMessage.error('更新组合失败: ' + error.message)
            })
          } else {
            // 创建新组合
            store.dispatch('addPortfolio', portfolioData).then(() => {
              ElMessage.success('组合创建成功')
              // 关闭预览对话框（如果打开）
              previewDialogVisible.value = false
              // 返回组合列表页面
              router.push('/portfolio-management')
            }).catch(error => {
              ElMessage.error('创建组合失败: ' + error.message)
            })
          }
        } else {
          return false
        }
      })
    }
    
    // 取消操作
    const cancel = () => {
      router.push('/portfolio-management')
    }
    
    return {
      portfolioForm,
      form,
      rules,
      fundSearchKeyword,
      previewDialogVisible,
      strategies,
      funds,
      selectedFundsDetails,
      filteredAvailableFunds,
      isValidWeights,
      isEdit,
      handleStrategyChange,
      generatePortfolio,
      addFundToPortfolio,
      removeFund,
      previewPortfolio,
      submitForm,
      cancel
    }
  }
}
</script>

<style scoped>
.portfolio-create-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.fund-selection-container {
  display: flex;
  gap: 20px;
}

.fund-list {
  flex: 1;
}

.fund-list h4 {
  margin-top: 0;
  margin-bottom: 10px;
}

.fund-list .el-input {
  margin-bottom: 10px;
}

.red-text {
  color: #f56c6c;
}

.green-text {
  color: #67c23a;
}

.chart-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}
</style> 